package main

import (
	"os"
	"tieup/internal/config"
	"tieup/internal/model"
	"tieup/internal/routes"
	"tieup/pkg/database"
	"tieup/pkg/redis"

	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func main() {
	// 初始化zerolog
	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
	logger := zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().Timestamp().Logger()
	log.Logger = logger

	// 加载配置
	cfg, err := config.LoadConfig("./internal/config")
	if err != nil {
		log.Fatal().Err(err).Msg("Error loading config")
	}

	// 设置Gin模式
	if cfg.Server.Env == "production" {
		gin.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
	}

	// 初始化数据库
	db, err := database.NewDB(cfg.Database)
	if err != nil {
		log.Fatal().Err(err).Msg("Database connection failed")
	}
	sqlDB, _ := db.DB()
	defer sqlDB.Close()

	// 初始化Redis
	if err := redis.Initialize(cfg.Redis); err != nil {
		log.Fatal().Err(err).Msg("Failed to connect to Redis")
	}
	defer redis.Client.Close()

	// 自动迁移模型
	if err := model.AutoMigrate(db); err != nil {
		log.Fatal().Err(err).Msg("Auto migration failed")
	}

	// 设置路由
	router := routes.SetupRouter(db, *cfg)

	// 启动服务器
	if err := router.Run(":" + cfg.Server.Port); err != nil {
		log.Fatal().Err(err).Msg("Failed to start server")
	}
}
